from typing import Tuple, List
from venv import logger

from fastapi import Request
from sqlalchemy.orm import Session

from core.dao.cms_gaode_fence_dao import CmsGaodeFenceDao
from core.entity.vo.common import CrudResponse
from core.entity.vo.view_models import CmsGaodeFenceVO, PaginationQuery, CmsGaodeFenceResponse, PaginationQueryForPage
from core.service.gaode.gaode_fence_service import GaodeFenceService


class CmsGaodeFenceService:
    """
    高德终端service
    """

    @classmethod
    def get_cms_gaode_fence_by_id(cls, result_db: Session, id: int):
        """
        获取参数配置列表信息service
        :param result_db: orm对象
        :param id: id
        :return: 参数配置列表信息对象
        """
        cms_gaode_fence = CmsGaodeFenceDao.get_cms_gaode_fence_by_id(result_db, id)

        return cms_gaode_fence

    @classmethod
    def get_cms_gaode_fence_by_fence_id(cls, result_db: Session, fence_id: str):
        """
        获取参数配置列表信息service
        :param result_db: orm对象
        :param fence_id: 高德终端id
        :return: 参数配置列表信息对象
        """
        cms_gaode_fence = CmsGaodeFenceDao.get_cms_gaode_fence_by_fence_id(result_db, fence_id)

        return cms_gaode_fence

    @classmethod
    def get_cms_gaode_fence_like_name(cls, result_db: Session, fence_name: str):
        """
        获取参数配置列表信息service
        :param result_db: orm对象
        :param query_object: 查询参数对象
        :return: 参数配置列表信息对象
        """
        cms_gaode_fence_list = CmsGaodeFenceDao.get_cms_gaode_fence_like_name(result_db, fence_name)

        return cms_gaode_fence_list

    @classmethod
    async def add_cms_gaode_fence(cls, request: Request, result_db: Session, cms_gaode_fence: CmsGaodeFenceVO):
        """
        新增参数配置信息service
        :param request: Request对象
        :param result_db: orm对象
        :param cms_gaode_fence: 新增参数配置对象
        :return: 新增参数配置校验结果
        """
        if cms_gaode_fence.fence_type == "district":
            result = GaodeFenceService.add_polygon_fence(cms_gaode_fence.service_id, cms_gaode_fence.fence_name,
                                                         cms_gaode_fence.fence_desc, cms_gaode_fence.polygon_points)
            if result['errcode'] == 10000:
                try:
                    cms_gaode_fence.fence_id = result['data']['gfid']
                    CmsGaodeFenceDao.add_cms_gaode_fence_dao(result_db, cms_gaode_fence)
                    result_db.commit()
                    result = dict(is_success=True, message='新增成功')
                except Exception as e:
                    result_db.rollback()
                    result = dict(is_success=False, message=str(e))
            else:
                result = dict(is_success=False, message=str(result['errmsg']))
        else:
            result = dict(is_success=False, message=str("暂不支持该围栏类型-" + cms_gaode_fence.fence_type))
        return CrudResponse(**result)

    @classmethod
    def edit_cms_gaode_fence(cls, request: Request, result_db: Session, cms_gaode_fence: CmsGaodeFenceVO):
        """
        编辑参数配置信息service
        :param request: Request对象
        :param result_db: orm对象
        :param cms_gaode_fence: 编辑参数配置对象
        :return: 编辑参数配置校验结果
        """
        result = GaodeFenceService.update_polygon_fence(cms_gaode_fence.service_id, cms_gaode_fence.fence_id,
                                                        cms_gaode_fence.fence_name, cms_gaode_fence.fence_desc,
                                                        cms_gaode_fence.polygon_points)
        if result['errcode'] == 10000:
            try:
                edit_post = cms_gaode_fence.dict(exclude={"cars", "car_numbers"})
                CmsGaodeFenceDao.edit_cms_gaode_fence_dao(result_db, edit_post)
                result_db.commit()
                result = dict(is_success=True, message='修改成功')
            except Exception as e:
                result_db.rollback()
                result = dict(is_success=False, message=str(e))
        else:
            result = dict(is_success=False, message=str(result['errmsg']))
        return CrudResponse(**result)

    @classmethod
    def delete_cms_gaode_fence(cls, result_db: Session, id: int, service_id: str, fence_id: str):
        """
        删除菜单信息service
        :param result_db: orm对象
        :param id: id
        :param service_id: 服务编码
        :param fence_id: 围栏编码
        :return: 删除终端
        """
        if id is not None:
            result = GaodeFenceService.delete_fence(service_id, fence_id)
            if result['errcode'] == 10000 or result['errcode'] == 20003:
                try:
                    CmsGaodeFenceDao.delete_cms_gaode_fence_dao(result_db, id)
                    result_db.commit()
                    result = dict(is_success=True, message='删除成功')
                except Exception as e:
                    result_db.rollback()
                    result = dict(is_success=False, message=str(e))
            else:
                result = dict(is_success=False, message=str(result['errmsg']))
        else:
            result = dict(is_success=False, message='传入id为空')
        return CrudResponse(**result)

    @classmethod
    def list_cms_gaode_fences(cls, db: Session, query: PaginationQuery) -> Tuple[List[CmsGaodeFenceVO], int]:
        try:
            fence_list, total = CmsGaodeFenceDao.get_fence_list(db, query)

            # Convert to Pydantic-compatible models
            # items = [
            #     CmsGaodeFenceVO.from_orm(fence)
            #     for fence in fence_list
            #     if fence.cars is not None
            # ]

            return CmsGaodeFenceResponse(data=fence_list, total=total)

        except Exception as e:
            logger.exception("Failed to fetch fences")
            raise e

# @classmethod
# def list_cms_gaode_fences(cls, db: Session, query: PaginationQuery) -> Tuple[List[CmsGaodeFenceVO], int]:
#             try:
#                 fence_list, total = CmsGaodeFenceDao.get_fence_list(db, query)
#                 return CmsGaodeFenceResponse(data=fence_list, total=total)
#             except Exception as e:
#                 logger.exception("Failed to fetch fences")
#                 raise e
